package com.ayf.payment.game.api.service.payment.cyf;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.bean.BaseResData;
import com.ayf.payment.game.api.dto.OrderAndMerchantDTO;
import com.ayf.payment.game.api.dto.platform.MerchantPaymentProductDTO;
import com.ayf.payment.game.api.dto.platform.PaymentChannelDTO;
import com.ayf.payment.game.api.entity.Order;
import com.ayf.payment.game.api.entity.Partition;
import com.ayf.payment.game.api.exception.NullSetException;
import com.ayf.payment.game.api.httpclient.HttpUtils;
import com.ayf.payment.game.api.service.payment.IPaymentService;
import com.ayf.payment.game.api.service.payment.cyf.util.CyfSignUtil;
import com.ayf.payment.game.api.utils.BigDecimalUtil;
import com.ayf.payment.game.api.utils.DateUtils;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Service
public class CYFPaymentService extends IPaymentService {

    @Override
    public Map<String, Object> paymentUtil(Order order, Partition partition, String orderCreateStr, String traceId, String redirectUrl) {
        Map<String, Object> map=new HashMap<>();
        MerchantPaymentProductDTO merchantPaymentProductDTO = systemInitialization.productDTO(order.getPayTypeId());
        PaymentChannelDTO paymentChannelDTO = systemInitialization.channelDTO(merchantPaymentProductDTO.getcId());
        BigDecimal actualOrderAmt = getActualOrderAmt(order.getAmount(),paymentChannelDTO.getId(),partition.getMerchantId());
        BaseResData baseResData = orderCreate(traceId,order,paymentChannelDTO,redirectUrl,actualOrderAmt);
        String orderCreateUrl = "";
        if (baseResData.isProcessing()){
            LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 传易付下单失败 请求接口成功，接口响应超时", traceId, order.getMerchantId(), order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (baseResData.isSuccess()) {
            String rpsData = baseResData.getData();
            JSONObject jsonData = JSONObject.parseObject(rpsData);
            boolean retCode = jsonData.getBoolean("Success");
            if (retCode){
                orderCreateUrl = jsonData.getString("Data");
                if (StringUtils.isEmpty(orderCreateUrl)){
                    LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 传易付下单失败 请求接口成功，接口返回报文 Data为空",traceId,order.getMerchantId(), order.getMerchantOrderNo());
                    throw new NullSetException(traceId + "下单失败，请稍后重试！");
                }
            } else {
                String Code = jsonData.getString("Code");
                String retMsg = jsonData.getString("Message");
                LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 传易付下单失败 请求接口成功，接口返回失败 Code:{} Message:{}",traceId,order.getMerchantId(), order.getMerchantOrderNo(),Code,retMsg);
                throw new NullSetException(traceId + "下单失败，请稍后重试！");
            }
        } else {
            LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 传易付下单失败 请求接口失败 Code:{} Message:{}",traceId,order.getMerchantId(), order.getMerchantOrderNo(),baseResData.getRespCode(),baseResData.getRespMsg());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        LogPortal.info("{} 商户ID[{}] 商户订单号[{}] 传易付下单 通道支付URL[{}]", traceId, order.getMerchantId(), order.getMerchantOrderNo(),orderCreateUrl);
        order.setRandomAmt(BigDecimal.ZERO);
        order.setPayChannleName(paymentChannelDTO.getName());
        order.setPayChannleId(paymentChannelDTO.getId());
        order.setPayTypeId(merchantPaymentProductDTO.getProductId());
        order.setPayTypeName(merchantPaymentProductDTO.getProductName());
        order.setMerchantIncome(BigDecimal.ZERO);
        order.setPlatformIncome(BigDecimal.ZERO);
        order.setFee(BigDecimal.ZERO);
        order.setChannelIncome(BigDecimal.ZERO);
        orderMapper.insertSelective(order);
        map.put("code", "003");
        map.put("RedirectUrl",orderCreateUrl);
        return map;
    }


    private BaseResData orderCreate(String traceId,Order order,PaymentChannelDTO paymentChannelDTO,String redirectUrl,BigDecimal actualOrderAmt){
        String methodName = "传易付下单";
        String KeyValue = paymentChannelDTO.getChannelKey();
        String parter = paymentChannelDTO.getAccountNumber();
        String returnUrl=paymentChannelDTO.getReturnUrl();
        String AuthorizationURL = paymentChannelDTO.getPaymentUrl();
        if (StringUtils.isEmpty(AuthorizationURL)){
            LogPortal.error("{} 失败，通道下单地址不能为空，订单号:{}",traceId,order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (!AuthorizationURL.endsWith("/")){
            AuthorizationURL=AuthorizationURL.concat("/");
        }
        if (StringUtils.isEmpty(returnUrl)){
            LogPortal.error("{} 失败，异步通知地址不能为空，订单号:{}",traceId,order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (!returnUrl.endsWith("/")){
            returnUrl=returnUrl.concat("/");
        }

        if (!redirectUrl.endsWith("/")){
            redirectUrl=redirectUrl.concat("/");
        }
        AuthorizationURL=AuthorizationURL.concat("Main/Gateway");
        Map<String,String> reqParam = new TreeMap<>();
        reqParam.put("PayType_Code","hmq");
        reqParam.put("Notify_Url",returnUrl.concat("gameapip/v/cyf/pay/notify"));
        reqParam.put("Total_Fee",String.valueOf(BigDecimalUtil.yuanToFen(actualOrderAmt)));
        reqParam.put("Return_Url",redirectUrl.concat("gws/loading.html?orderNo=").concat(order.getMerchantOrderNo()));
        reqParam.put("Order_id",order.getMerchantOrderNo());
        reqParam.put("Merchant_Id",parter);
        reqParam.put("Charset","utf8");
        reqParam.put("GetUrlType","1");

        String sign= CyfSignUtil.getSign(traceId,methodName,reqParam,KeyValue);
        reqParam.put("sign",sign);
        BaseResData baseResData = HttpUtils.sendPostForm(traceId,methodName,AuthorizationURL,reqParam);
        return baseResData;
    }


    @Override
    public void queryPayOrder(OrderAndMerchantDTO dto, String traceId) {

    }

    private static void testOrderCreate(){
        PaymentChannelDTO paymentChannelDTO = getTestPaymentChannelDTO();
        Order order = new Order();
        Date currentDate = DateUtils.getNowDate();
        String orderCreateStr = DateUtils.dateToString(currentDate, DateUtils.formatPattern_full_03);
        String orderNo = "M" + orderCreateStr + SnowFlakeUtils.getUniqueId();
        order.setMerchantOrderNo(orderNo);
        order.setCreateTime(currentDate);
        order.setAmount(BigDecimal.valueOf(1));
        order.setMerchantId(1000);
        String traceId = SnowFlakeUtils.getTraceId28();
        String redirectUrl = "http://uatxy.xyouplay.com";
        CYFPaymentService xinYou2PaymentService = new CYFPaymentService();
        BaseResData baseResData = xinYou2PaymentService.orderCreate(traceId,order,paymentChannelDTO,redirectUrl,order.getAmount());
        System.out.println("传易付下单返回报文:"+JSONObject.toJSONString(baseResData));
    }

    private static PaymentChannelDTO getTestPaymentChannelDTO(){
        PaymentChannelDTO paymentChannelDTO = new PaymentChannelDTO();
        paymentChannelDTO.setPaymentUrl("https://cyfapi.sfcqlt.com");
        paymentChannelDTO.setReturnUrl("http://uatxy.xyouplay.com");
        paymentChannelDTO.setChannelKey("408ef32c065e4e468c50efbba341c89a");
        paymentChannelDTO.setAccountNumber("1004");// 商户ID
        return paymentChannelDTO;
    }

    public static void main(String[] args) {
        testOrderCreate();
    }

}
